package hos.okhttp.convert;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;

import hos.http.HttpLogUtils;
import hos.http.HttpRequest;
import hos.http.converter.HttpConvert;
import hos.okhttp.utils.OkHttpResponseUtils;
import okhttp3.Response;

/**
 * <p>Title: ResponseConverter </p>
 * <p>Description: Response转换器 </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023/2/18 18:38
 */
public abstract class HttpResponseConverter implements HttpConvert<Response> {

    @SuppressWarnings("unchecked")
    @Override
    public <R> R onConvert(HttpRequest<?> request, Type succeed, Response response) throws IOException {
        try {
            Object requireData = OkHttpResponseUtils.requireData(succeed, response);
            if (!(requireData instanceof Response) && !(requireData instanceof File)) {
                HttpLogUtils.responseLog(request, requireData.toString());
            }
            return (R) requireData;
        } catch (IOException e) {
            // 解析异常,重新解析
            return parseJson(request,succeed, OkHttpResponseUtils.requireResponse(response));
        }
    }

    public abstract <D> D parseJson(HttpRequest<?> request, Type succeed, Response response) throws IOException;
}
